package com.gillion.grule.client.sync;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.util.HashMap;
import java.util.Map;
import org.apache.curator.framework.recipes.cache.TreeCacheListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;


@Component
public class ZookeeperHttpRuleCacheProvider extends ZookeeperRuleCacheProvider implements TreeCacheListener
{
    private String url;
    private static final Logger LOGGER = LoggerFactory.getLogger(ZookeeperHttpRuleCacheProvider.class);


    synchronized DroolsRulePackage loadRule(String groupId, String artifactId, String version) {
        Map<String, Object> params = new HashMap<>();
        params.put("groupId", groupId);
        params.put("artifactId", artifactId);
        params.put("version", version);
        LOGGER.info("请求地址：" + this.url + "，请求groupId：" + groupId + "，请求规则编码：" + artifactId + "，请求版本号：" + version);

        String httpResult = HttpUtil.post(this.url, params);
        JSONObject jo = JSONObject.parseObject(httpResult);
        DroolsRulePackage droolsRulePackage = (DroolsRulePackage)JSON.parseObject(jo.get("data").toString(), DroolsRulePackage.class);
        droolsRulePackage.compile(getRuleCompiler());
        return droolsRulePackage;
    }
    public void setUrl(String url) {
        this.url = url;
    }
}